package edu.umn.contactviewer.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;

import edu.umn.contactviewer.Contact;
import edu.umn.contactviewer.constant.ContactViewerConstants;

public class PostContactAsyncTask extends
		AsyncTask<Contact, Void, PostContactResponseData> {

	private static final String TAG = "PutContacts";
	private static final String EMPTY = "";
	private Context context;
	private PostContactResponseListener putContactResponseListener;
	private final Gson gson = new Gson();

	public PostContactAsyncTask(
			PostContactResponseListener putContactResponseListener,
			Context context) {
		this.putContactResponseListener = putContactResponseListener;
		this.context = context;
	}

	@Override
	protected PostContactResponseData doInBackground(Contact... contacts) {
		PostContactResponseData putContactsResponseData = null;
		Contact contactToPost = contacts[0];
		if (null != contactToPost) {
			AndroidHttpClient client = AndroidHttpClient.newInstance("Android",
					null);
			try {
				HttpUriRequest request = new HttpPost(
						createPostURLString(contactToPost));
				HttpResponse response = client.execute(request);
				InputStream in = response.getEntity().getContent();
				String jsonResponse = readJsonResponse(in);
				putContactsResponseData = gson.fromJson(jsonResponse,
						PostContactResponseData.class);
			} catch (IOException ex) {
				Log.e(TAG + "IO Exception: ", ex.toString());
			} catch (Exception ex) {
				Log.e(TAG + "Exception: ", ex.toString());
			} finally {
				client.close();
			}
		}

		return putContactsResponseData;
	}

	private String createPostURLString(Contact contactToPost) {
		return ContactViewerConstants.WEB_SERVICE_URL
				+ ContactViewerConstants.SEPARATOR_QUERY_STRING
				+ ContactViewerConstants.API_KEY_MAPPING
				+ ContactViewerConstants.SEPARATOR_AND
				+ createContactPutRequestContent(contactToPost);
	}

	private String createContactPutRequestContent(Contact contact) {
		StringBuilder contactPutRequestContentBuilder = new StringBuilder("");
		contactPutRequestContentBuilder.append("name=");
		contactPutRequestContentBuilder.append(getContactStringValue(contact
				.getName()));
		contactPutRequestContentBuilder
				.append(ContactViewerConstants.SEPARATOR_AND);
		contactPutRequestContentBuilder.append("title=");
		contactPutRequestContentBuilder.append(getContactStringValue(contact
				.getTitle()));
		contactPutRequestContentBuilder
				.append(ContactViewerConstants.SEPARATOR_AND);
		contactPutRequestContentBuilder.append("email=");
		contactPutRequestContentBuilder.append(getContactStringValue(contact
				.getEmail()));
		contactPutRequestContentBuilder
				.append(ContactViewerConstants.SEPARATOR_AND);
		contactPutRequestContentBuilder.append("phone=");
		contactPutRequestContentBuilder.append(getContactStringValue(contact
				.getPhone()));
		contactPutRequestContentBuilder
				.append(ContactViewerConstants.SEPARATOR_AND);
		contactPutRequestContentBuilder.append("twitterId=");
		contactPutRequestContentBuilder.append(getContactStringValue(contact
				.getTwitterId()));
		return contactPutRequestContentBuilder.toString();
	}

	private String getContactStringValue(String contactString) {
		String value = EMPTY;
		try {
			value = URLEncoder.encode(null != contactString ? contactString
					: EMPTY, "utf-8");
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG, "Stupid encoder...");
		}
		return value;
	}

	private String readJsonResponse(InputStream in) throws IOException {
		String jsonResponse = "";
		BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
		String s = "";
		while ((s = buffer.readLine()) != null) {
			jsonResponse += s;
		}
		buffer.close();

		return jsonResponse;
	}

	@Override
	protected void onPostExecute(PostContactResponseData result) {
		super.onPostExecute(result);
		putContactResponseListener.onResponse(result);
	}
}
